<template>
  <el-dialog v-model="show" title="分配权限" width="30%">
    <el-tree
      ref="treeRef"
      :data="treeData"
      show-checkbox
      node-key="id"
      :props="defaultProps"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="ok"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { get, put, R } from '@/utils/http/request'
import {
  ref,
  reactive,
  toRefs,
  watch,
  onMounted,
  nextTick,
  getCurrentInstance,
} from 'vue'
import type { PropType } from 'vue'
import { ElTree } from 'element-plus'
import { CodeEnum } from '@/constants/http-code'
import { useVModels } from '@vueuse/core'

const emit = defineEmits(['update:show', 'refreshTable'])
const props = defineProps({
  /**
   * 是否显示弹窗
   */
  show: {
    type: Boolean,
    default: false,
  },

  roleId: {
    type: Number,
    default: 0,
  },
})

const { roleId } = toRefs(props)

const { show } = useVModels(props)

//const { } = toRefs(props);
const treeRef = ref<InstanceType<typeof ElTree>>()
const ok = async () => {
  //获取当前角色权限id列表
  const res = await get<R<number[]>>(
    `/role/permission/relation/pids/${roleId.value}`
  )

  //获取选中节点
  const check = treeRef.value?.getCheckedKeys() as number[]
  //获取半选中节点
  const halfCheck = treeRef.value?.getHalfCheckedKeys() as number[]

  //[1,2,3,4]
  //[3,2]
  //1 5
  //[1,2,3,4,3,2]
  const arr = res.data.concat([...check, ...halfCheck]).filter((v, i, arr) => {
    return arr.indexOf(v) === arr.lastIndexOf(v)
  })

  const add: number[] = []
  const del: number[] = []
  arr.forEach((v) => {
    if (res.data.indexOf(v) === -1) {
      add.push(v)
    } else {
      del.push(v)
    }
  })
  console.log(`添加: ${add}`)
  console.log(`删除: ${del}`)

  const res1 = await put<R<any>>('/role/permission/relation', {
    roleId: roleId.value,
    add,
    del,
  })

  if (res1.code === CodeEnum.UPDATE) {
    show.value = false
  }
}

const defaultProps = {
  children: 'children',
  label: 'title',
}

interface Tree {
  id: string
  title: string
  children: Tree[]
}

const treeData = ref<Tree[]>([])

const initTreeData = async () => {
  //获取菜单权限树结构
  const res = await get<R<Tree[]>>('/permission/all/tree')

  treeData.value = res.data
  setCheckedKeys()
}
initTreeData()

const setCheckedKeys = async () => {
  //获取前端选中节点
  const res = await get<R<number[]>>(
    `/role/permission/relation/check/pids/${roleId.value}`
  )
  //设置当前tree选中节点
  treeRef.value?.setCheckedKeys(res.data)
}
</script>

<style lang="scss" scoped></style>
